{% extends '__base__.html' %}

{% block title %}粘贴版{% endblock %}

{% block content %}
    <div class="container">
        <div class="row">
            <div class="col-md-8 pb-4">
                <textarea id="paste" style="width: 100%" rows="3" placeholder="paste conten here"></textarea>
            </div>
            <aside class="col-md-4 blog-sidebar">
                <div class="p-4 mb-3 bg-light rounded">
                    <h4 class="font-italic">
                        <span>用户信息</span>
                        <small class="float-right" style="cursor: pointer">
                            <a class="pr-3" id="exportAll" data-toggle="tooltip" data-placement="top" title="导出"><i class="fa fa-share-square-o"></i></a>
                        </small>
                    </h4>
                    {% if __user__ %}
                    <p class="mb-0">{{ __user__.name }}</p>
                    <p class="mb-0">{{ __user__.email }}</p>
                    {% else %}
                    <p class="mb-0">用户未登录</p>
                    {% endif %}
                  </div>
            </aside>
        </div>
        <div id="copy" class="row">
            {% for clipboard in clipboards %}
            <div class="col-sm-12 col-md-4 pb-4" style="cursor:pointer">
                <div class="card">
                    <div class="card-header" data-id="{{ clipboard.id }}">删除</div>
                    <textarea class="card-body" style="height: 100%;width: 100%;resize:none;" readonly rows="10">{{ clipboard.content }}</textarea>
                </div>
            </div>
            {% endfor %}
        </div>
        <div id="export" class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
                <textarea class="modal-content" style="resize: none;height: 80vh;" readonly></textarea>
            </div>
        </div>
    </div>
{% endblock %}
{% block beforebody %}
<script>
    let paste = document.querySelector('#paste')
    let copy = document.querySelector('#copy')
    copy.querySelectorAll('.card-body').forEach(el => {
        el.addEventListener('click', copyContent, false)
    })
    function copyContent(e) {
        let el = e.target
        if (document.body.createTextRange) {
            let range = document.body.createTextRange();
            range.moveToElementText(el);
            range.select();
        } else if (window.getSelection) {
            let selection = window.getSelection();
            let range = document.createRange();
            range.selectNodeContents(el);
            selection.removeAllRanges();
            selection.addRange(range);
        } else {
            console.log("can not select the el");
        }
        document.execCommand('Copy','false',null);
        console.log('复制: ' + el.innerHTML)
    }
    copy.querySelectorAll('.card-header').forEach(el => {
        el.addEventListener('click', deleteItem, false)
    })

    function deleteItem(event) {
        let id = event.target.dataset['id']
        if (confirm(" 是否删除[" + id + "] ")) {
            axios.get('/clipboard/delete/' + id)
              .then(function (response) {
                  // console.log(response);
                  if (response.status === 200) {
                      let data = response.data
                      if (data['code'] === 0) {
                        console.log('SUCCESS: ' + data['msg'])
                        let remove_item = document.querySelector('.card-header[data-id="' + id + '"]')
                        if (remove_item) {
                            remove_item.parentNode.parentNode.parentNode.removeChild(remove_item.parentNode.parentNode)
                        }
                      } else {
                          console.log('FAILED: ' + data['msg'])
                      }
                  }
              })
              .catch(function (error) {
                  console.log(error);
              });
        }
    }

    paste.addEventListener('paste', (event)=> {
        event.target.value = ''
        let data = event.clipboardData.getData('Text')
        sendmsg(data)
    })
    function creatCopyEl(data, id) {
        if (data.trim().length === 0) return false
        let div = document.createElement('div')
        let card_header = document.createElement('div')
        card_header.className = 'card-header'
        card_header.dataset['id'] = id
        card_header.innerText = "删除"
        let card_body = document.createElement('textarea')
        card_body.className = 'card-body'
        card_body.readOnly = "True"
        card_body.rows = "10"
        card_body.style = "height: 100%;width: 100%;resize:none;"
        card_body.innerHTML = data
        let card = document.createElement('div')
        card.className = 'card'
        card.appendChild(card_header)
        card.appendChild(card_body)
        div.appendChild(card)
        // div.innerHTML = data
        div.style = "cursor:pointer"
        div.className = "col-sm-12 col-md-4 pb-4"
        card_body.addEventListener('click', copyContent, false)
        card_header.addEventListener('click', deleteItem, false)
        return div
    }
    document.querySelector('#exportAll').addEventListener('click', () => {
        axios.get('/clipboard/items')
        .then(
            response => {
                if (response.status === 200) {
                    let data = response.data
                    if (data['code'] === 0) {
                        let items = data['msg']['items'] ? data['msg']['items'] : []
                        $('#export textarea').val(JSON.stringify(items, null, "\t"))
                        $('#export').modal('show')
                    } else {
                        console.log('FAILED: ' + data['msg'])
                    }
                }
            })
        .catch(function (error) {
            console.log(error);
        });
    
    
    }, false)
    function sendmsg(text) {
        axios.post('/clipboard', {
            text: text
          })
          .then(function (response) {
              // console.log(response);
              if (response.status === 200) {
                  let data = response.data
                  if (data['code'] === 0) {
                    console.log('SUCCESS: ' + data['msg'])
                    let div = creatCopyEl(text, data['msg'])
                    if (div) {
                        copy.insertBefore(div,copy.childNodes[0])
                    }
                  } else {
                      console.log('FAILED: ' + data['msg'])
                  }
              }
          })
          .catch(function (error) {
              console.log(error);
          });
    }
</script>
{% endblock %}
